package com.sskj.level.ui.fragment;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.level.R;
import com.sskj.level.R2;
import com.sskj.level.bean.BuySellEnum;
import com.sskj.level.bean.TradeListBean;
import com.sskj.level.component.DaggerUserDataComponent;
import com.sskj.level.presenter.EntrustFragmentPresenter;
import com.sskj.level.util.TipLevelUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.mvchelper.RefreshDataSource;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

@Route(path = RConfig.LEVEL_FRAGMENT_ENTRUST)//委托
public class EntrustFragment extends BaseFragment<EntrustFragmentPresenter> {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    private SlimAdapter<TradeListBean> slimAdapter;
    private MVCCoolHelper<List<TradeListBean>> mvcCoolHelper;
    private int curPos;
    private Disposable subscribe;
    @Inject
    UserViewModel userViewModel;
    @Autowired
    String code;
    private MaterialDialog cancelTip;

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden && mvcCoolHelper != null) {
            mvcCoolHelper.refresh();
        }
        super.onHiddenChanged(hidden);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.level_fragment_entrust;
    }

    @Override
    public EntrustFragmentPresenter getPresenter() {

        return new EntrustFragmentPresenter();
    }

    @Override
    public void initView() {
        DaggerUserDataComponent.create().inject(this);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        slimAdapter = SlimAdapter.create().register(R.layout.level_recy_item_entrust, new SlimInjector<TradeListBean>() {
            @Override
            public void onInject(TradeListBean data, IViewInjector injector, List payloads) {
                injector
                        .textColor(R.id.tv_mm, ContextCompat.getColor(App.INSTANCE, data.getOtype().equals(BuySellEnum.BUY.getType()) ? BuySellEnum.BUY.getColorRes() : BuySellEnum.SELL.getColorRes()))
                        .text(R.id.tv_mm, data.getOtype().equals(BuySellEnum.BUY.getType()) ? BuySellEnum.BUY.getTitle() : BuySellEnum.SELL.getTitle())//买入卖出
                        .text(R.id.tv_bz, data.getPname())//币种类型
                        .text(R.id.tv_time, data.getAdd_time())//时间
                        .text(R.id.tv_first_left, data.getMarketLimit())//类型
                        .text(R.id.level_fd_type, App.INSTANCE.getString(R.string.levelJavaEntrustFragment1) + data.getFdyk())//盈亏
                        .text(R.id.tv_first_right, NumberUtil.keep(data.getLeverage(),0))//data.getLeverage())//((int)Double.parseDouble(data.getLeverage())))//委托量
                        .text(R.id.tv_second_left, data.getWtprice1())//委托价
                        .text(R.id.tv_second_right, data.getNewprice())//最新价
                        .text(R.id.tv_third_left, data.getWtnum())//止盈价
                        .text(R.id.tv_third_right, data.getTotalprice())//手续费
                        .text(R.id.tv_four_left, data.getSxfee())//止损价
                        .clicked(R.id.tvCancel, v -> {
                            curPos = slimAdapter.getData().indexOf(data);
                            cancel();
                        });
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        RefreshDataSource<TradeListBean> refreshDataSource = new RefreshDataSource<TradeListBean>(coolRefreshView) {
            @Override
            public Flowable<List<TradeListBean>> loadData() {
                return mPresenter.getTradeListFlow(code);
            }
        };
        mvcCoolHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcCoolHelper.setDataSource(refreshDataSource);
        mvcCoolHelper.setAdapter(slimAdapter);
        mvcCoolHelper.refresh();
        startTimer();
    }

    /**
     * 定时刷新委托单的价格
     */
    private void startTimer() {
        DisposUtil.close(subscribe);
        subscribe = Flowable.interval(0, 5, TimeUnit.SECONDS)
                .onBackpressureDrop()
                .subscribe(i -> mPresenter.getTradeList(code));
    }

    /**
     * 撤销订单
     */
    private void cancel() {
        TradeListBean dataItem = slimAdapter.getDataItem(curPos);
        cancelTip = TipLevelUtil.showTradeCancel(getActivity(), dataItem.getOtype(), dataItem.getWtnum(), dataItem.getWtprice1(), () -> {
            cancelTip.dismiss();
            mPresenter.cancelOrder(slimAdapter.getDataItem(curPos).getEn_id() + "");

        });
        cancelTip
                .show();
    }

    public void refresh() {
        mvcCoolHelper.refresh();
    }

    @Override
    public void onDestroy() {
        DisposUtil.close(subscribe);

        super.onDestroy();
    }

    public void updateUI(List<TradeListBean> data) {
        if (slimAdapter != null) {
            if (data.size() > 0 && slimAdapter.getData().size() == 0) {
                mvcCoolHelper.refresh();
            }
            slimAdapter.updateData(data);
        }
    }

    public void cancelOrderSuccess() {
        userViewModel.update();
        refresh();
    }
}
